<?php
# http://projects:8081/cdapp-2kt-api/api/request_atcos.php
# http://projects:8081/cdapp-2kt-api/api/request_atcos.php?cookie=1
die();

include_once '_portal.php';

// force load cookie only
$load_cookie = isset($_GET['cookie']) && $_GET['cookie'] == 1 ? 1 : 0;
if ($load_cookie) {
  request_cookie(true);
}

// terminate request ATCOS
if (get_variable('STOP_ALL_NETWORK') === 1) {
  die('Network Stoped');
}
if (get_variable('STOP_ATCOS') === 1) {
  die('ATCOS Stoped');
}

function request_atcos($apis) {
  $last_request = get_variable('ATCOS_LAST_REQUEST');
  $timestamp = timestamp();
  $next_request = $last_request + ATCOS_REQUEST_TTL;
  if ($last_request && $timestamp < $next_request) {
    time_sleep_until($next_request / 1000);
  }
  save_variable('ATCOS_LAST_REQUEST', timestamp());
  request_cookie();
  $cookie = get_cookie();
  if (!$cookie) {
    return null;
  }

  // if payload is invalid
  $request_type = gettype($apis);
  if ($request_type != 'string' && $request_type != 'array') {
    return null;
  }
  $script_name = strtoupper(basename(debug_backtrace()[0]['file'], '.php'));
  $server_id = $cookie['server'];
  $cookie_file = $cookie['file'];
  $account = $cookie['account'];
  $base_url = ATCOS_BASE_URLS_2[$server_id];
  $cookie_jar = dirname(__FILE__) . "\\atcos_cookie\\{$cookie_file}.txt";

  $result = null;
  if ($request_type == 'string') {
    $result = send_request($apis, $cookie_jar, $base_url);
  } elseif ($request_type == 'array') {
    $result = [];
    foreach ($apis as $api) {
      $result[] = send_request($api, $cookie_jar, $base_url);
    }
  }
  $message = [
    'message' => "CH{$server_id} / {$account} / {$script_name}",
    'server' => $server_id,
    'account' => $account,
    'script' => $script_name,
    'url' => $base_url,
    'input' => $apis,
    'output' => $result,
  ];
  logdb('REQUEST_ATCOS', $message, 'INFO');
  return $result;
}

function send_request($api, $cookie_jar, $base_url) {
  // logdb('REQUEST_ATCOS_TX', "{$base_url}{$api}", 'INFO');
  // 到指定页面获取数据
  $ch = curl_init();
  $url = $base_url . $api;
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_TIMEOUT, ATCOS_REQUEST_TIMEOUT);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
  $html = curl_exec($ch);
  curl_close($ch);
  // logdb('REQUEST_ATCOS_RX', "{$html}", 'INFO');
  // output
  if ($html == '') {
    return [];
  }
  return json_decode($html, true);
}

function get_cookie() {
  $limit = time() - COOKIE_EXPIRE;
  $sql = "SELECT `file`, `account`, `server` FROM `2kt_atcos_cookie` WHERE `version` >= {$limit}";
  $result = exec_sql($sql);
  if ($result && count($result) > 0) {
    $idx = mt_rand(0, count($result) - 1);
    $selected = query_parse([$result[$idx]])[0];
    return $selected; // {file,server}
  } else {
    return null;
  }
}

function request_cookie($manually = false) {
  $time = timestamp();
  if (!$manually) {
    $last_tx = get_variable('LAST_COOKIE_REQUEST');
    if (($last_tx != null) && ($time - $last_tx < COOKIE_TTL)) {
      return null;
    }
  }
  save_variable('LAST_COOKIE_REQUEST', $time);
  // create table {
  $sql = "CREATE TABLE IF NOT EXISTS `2kt_atcos_cookie` (
    `file` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
    `account` varchar(16) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
    `server` tinyint(4) NOT NULL DEFAULT '0',
    `version` int(16) NOT NULL DEFAULT '-1',
    PRIMARY KEY (`file`)
   ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
  exec_sql($sql);
  $sql = "INSERT IGNORE INTO `2kt_atcos_cookie`(`file`, `account`, `server`, `version`) VALUES ";
  for ($j = 0; $j < 3; $j++) {
    foreach ([3, 6, 7, 8, 14, 11] as $i) {
      $seat = 'TM' . ($i < 10 ? '0' : '') . $i;
      $file = $seat . '@' . $j;
      $sql .= "('{$file}','{$seat}',{$j},-1),";
    }
  }
  $sql = rtrim($sql, ',');
  $sql .= ';';
  $created = exec_sql($sql);
  if ($manually) {
    echo $sql . PHP_EOL . PHP_EOL;
  }
  // find 1st expired cookie
  $version_limit = time() - COOKIE_UPDATE;
  $sql = "SELECT `account`, `server` FROM `2kt_atcos_cookie` WHERE `version` < {$version_limit}";
  $query = exec_sql($sql);
  if ($query && count($query) > 0) {
    $query = query_parse([$query[mt_rand(0, count($query) - 1)]]);
    $expired = $query[0]; // expired: {account,server}
    $server = $expired['server'];
    $account = $expired['account'];
    $url = ATCOS_BASE_URLS_2[$server];
    $url .= "loginGet?userName={$account}&pwd={$account}";
    $cookie_file = $account . '@' . $server;
    $cookie_jar = dirname(__FILE__) . "\\atcos_cookie\\{$cookie_file}.txt";
    $ch = curl_init(); // request cookie
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, ATCOS_REQUEST_TIMEOUT);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
    $html = curl_exec($ch);
    curl_close($ch);

    // save cookie
    $file = $account . '@' . $server;
    $version = time();
    $sql = "UPDATE `2kt_atcos_cookie` SET `version`={$version} WHERE `file`='{$file}'";
    $saved = exec_sql($sql);

    // output result
    $output = ['account' => $account, 'server' => $server];
    $message = [
      'message' => "CH{$server} / {$account} / UPDATED COOKIE",
      'server' => $account,
      'account' => $account,
    ];
    logdb('REQUEST_ATCOS_COOKIE', $message, 'INFO');

    if ($manually) {
      output($output);
    }
    return $output;

  } else {
    if ($manually) {
      output(null);
    }
    return null;
  }
}